var express = require('express');
const { path } = require('../app');
var router = express.Router();

//导入lowdb
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync( __dirname+'/../db/db.json');
const db = low(adapter); 

//导入shortid 
const shortid = require('shortid');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//记账本列表
router.get('/account', function(req, res, next) {

  let accounts = db.get("posts").value();
  res.render('accountlist',{accounts:accounts});
});

//添加记录
router.get('/account/create', function(req, res, next) {
  res.render('accountcreate');
});

//表单数据提交
router.post('/account', function(req, res, next) {

    let id = shortid.generate();
     db.get('posts')
     .unshift({id:id, ...req.body})
     .write();
    res.render('success',{msg:"添加成功了哦~~~",url:"/account"});
  });


//删除记录
router.get('/account/:id', (req, res) => {
  //获取 params 的 id 参数
  let id = req.params.id;
  //删除
  db.get('posts').remove({id:id}).write();
  //提醒
  res.render('success', {msg: '删除成功~~~', url: '/account'});
});


 /*  db操作

 // Set some defaults
  db.defaults({ posts: [], user: {} })  可以自定义 里面的对象
  .write()
 //写入数据
// db.get('posts').push({id: 2, title: '今天天气还不错~~'}).write(); 向后添加
// db.get('posts').unshift({id: 3, title: '今天天气还不错~~'}).write();  向前添加
//获取单条数据
// let res = db.get('posts').find({id: 1}).value();
// console.log(res);

//获取数据
// console.log(db.get('posts').value());

//删除数据
// let res = db.get('posts').remove({id: 2}).write();
// console.log(res);

//更新数据
// db.get('posts').find({id: 1}).assign({title: '今天下雨啦!!!'}).write() */
module.exports = router;
